from flask import Flask
from flask import request
import hashlib
import base64

app = Flask(__name__)


# OneNET全局推送链接
@app.route("/he/data/push/global", methods=['GET', 'POST'])
def he_data_push_global():
    if request.method == 'POST':
        print('**** Receive Post Data *****')
        print(request.data)
        # todo send email\msg\weichat\miniprogram
        return 'POST SUCCESS'
    msg = request.args.get('msg') or None
    signature = request.args.get('signature') or None
    nonce = request.args.get('nonce') or None
    if not all([msg, signature, nonce]):
        return 'invalid parameter'
    token = '202003312302001'    # 这里是URL添加时填写的Token
    # 第1步 计算MD5
    params_str = token + nonce + msg
    md5 = hashlib.md5(params_str.encode('utf-8')).digest()
    # 第2步 编码为Base64字符串值
    b64_str = base64.b64encode(md5)
    # 第3步 将上一步中Base64字符串值通过URL Decode
    b64_str = b64_str.decode('utf-8')
    # 第4步 将URL Decode编码后的值与请求参数signature的值进行对比
    if signature == b64_str:
        return msg
    return 'invalid token'


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

